using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace port
{
    public class listener
    {
        static bool _continue;
        SerialPort _serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
        public  void MainListener()
        {
            string message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread readThread = new Thread(Read);
            
            _serialPort.ReadTimeout = 1000;
            _serialPort.WriteTimeout = 1000;
            _serialPort.Open();
            _continue = true;
            readThread.Start();

            Console.WriteLine("Type QUIT to exit");


            while (_continue)
            {
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    this.Read();
                }
            }

            readThread.Join();
            _serialPort.Close();
        }

        public void  Read()
        {
            while (_continue)
            {
                try
                {
                    _serialPort.RtsEnable = true;
                    int message = _serialPort.ReadByte();
                    Console.WriteLine(message.ToString());
                }
                catch (TimeoutException) 
                { 
                  
                }
            }
        }
    }
}

